package org.simpleframework.mvc.render.impl;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.simpleframework.mvc.RequestProcessorChain;
import org.simpleframework.mvc.render.ResultRender;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * json数据认渲染器
 *
 * @author: Oliver
 * @time: 2020/12/29/19:59
 */
@Slf4j
public class JsonResultRender implements ResultRender {
    private Object res;

    public JsonResultRender(Object result) {
        this.res = result;
    }

    /**
     * 将对象转成json写回到页面
     *
     * @param chain 请求执行链
     * @throws Exception
     */
    @Override
    public void render(RequestProcessorChain chain) throws Exception {
        // 设置响应头
        chain.getResponse().setContentType("application/json");
        chain.getResponse().setCharacterEncoding("UTF-8");
        // 响应流写入经过gson格式化之后的处理结果 try -catch-resource
        Gson son = new Gson();
        try (PrintWriter writer = chain.getResponse().getWriter()) {
            writer.write(son.toJson(res));
            writer.flush();
        } catch (Exception e) {
            log.error("JsonResultRender : json writer is failed {} , can stream Exception or gson Exception", son.toJson(res));
        }
    }
}
